package org.wmq.javafxmapcollectioncs.mapper.impl;


import java.io.*;

public class CommentMapperImplByFileSystem implements CommentMapper {
    public static final String FILE_PREFIX = "D:\\map_collection_data\\comment_data\\";
    @Override
    public String selectById(Long id) {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return null;
        }
        try (FileInputStream fileInputStream = new FileInputStream(file)){
            return new String(fileInputStream.readAllBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Long id,String comment) throws IOException {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(comment.getBytes());
        fileOutputStream.close();
    }

    @Override
    public void update(Long id,String comment) {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return;
        }
        try(FileOutputStream fileOutputStream = new FileOutputStream(file)){
            fileOutputStream.write(comment.getBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return;
        }
        file.delete();
    }
}
